package com.example.springcloud.controller;

import com.example.springcloud.entities.CommonResult;
import com.example.springcloud.entities.Payment;
import com.example.springcloud.service.PaymentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

/**
 * @Description: 控制器
 * @Author wenlinyu
 * @Date: 2021/3/12 14:54
 * @Version 1.0
 */
@RestController
public class PaymentController {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private PaymentService paymentService;
    @Value("${server.port}")
    private String serverPort;

    @GetMapping("/payment/lb")
    public String getPaymentLB() {
        return serverPort;
    }

    /**
     * 插入
     * @param payment
     * @return
     */
    @PostMapping(value = "/payment/create")
    public CommonResult create(@RequestBody Payment payment) {
        int result = paymentService.create(payment);
        logger.info("*********插入结果：{}", result);
        if (result > 0) {
            return new CommonResult(200, "插入数据成功，serverPort: " + serverPort, payment);
        } else {
            return new CommonResult(444, "插入数据失败", null);
        }
    }

    /**
     * 查询
     * @param id
     * @return
     */
    @GetMapping(value = "/payment/get/{id}")
    public CommonResult getPaymentById(@PathVariable("id") Long id) {
        Payment payment = paymentService.getPaymentById(id);
        logger.info("**********查询结果：{}", payment);
        if (payment != null) {
            return new CommonResult(200, "查询成功，serverPort: " + serverPort, payment);
        } else {
            return new CommonResult(444, "没有对应记录，查询id:" + id, null);
        }
    }

    /**
     * 故意设置超时演示出错情况
     * @return
     */
    @GetMapping(value = "/payment/feign/timeout")
    public String paymentFeignTimeout() {
        // 模拟业务逻辑耗时3秒
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return serverPort;
    }
}
